/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.zzz.view.teacherControl;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.*;

import org.zzz.controller.AttendanceController;
import org.zzz.controller.StudentController;
import org.zzz.controller.StudentCourseController;
import org.zzz.entity.Class;
import org.zzz.entity.Student;
import org.zzz.entity.StudentCourse;
import org.zzz.utils.Result;
import org.zzz.utils.ResultEnum;
import org.zzz.view.util.UiUtil;

import java.util.List;
import java.util.UUID;

/**
 *
 * @author ASUS
 */
public class teacherRecordStatusFrame extends javax.swing.JFrame {

    /**
     * Creates new form teacherRecordStatusFrame
     */
    public teacherRecordStatusFrame(){
        
    }

    public teacherRecordStatusFrame(teacherRecordFrame trf,String date, Class room,String teacherId) {
        this.trf = trf;
        this.teacherId = teacherId;
        initComponents();
        init(date,room);         //初始化
    }

    private void init(String date,Class room){
        StudentController studentController = new StudentController();
        StudentCourseController studentCourseController = new StudentCourseController();
        String classId = room.getId();
        this.aClass=room;
        this.date=date;
        this.room=room.getName();
        this.setTitle(this.room+"的考勤状况");
        UiUtil.setFrameCenter(this);
        this.jLabel6.setText(date);
        this.jLabel7.setText(this.room);
        this.setResizable(false);
        //设置考勤状态为组合框形式
        String[] items={"出勤","请假","旷课","迟到","早退"};
        JComboBox comboBox = new JComboBox(items);
        DefaultCellEditor dc = new DefaultCellEditor(comboBox);
        this.stats.getColumnModel().getColumn(3).setCellEditor(dc);


        Result<List<Student>> studentResult = studentController.listStudentByClassId(classId);
        if (studentResult.getStatus() == ResultEnum.SUCCESS.getStatus()){
            //该班级存在学生
            //遍历
            List<Student> students = studentResult.getData();
            for (Student student : students) {
                Result<String> scResult = studentCourseController.getCourseNamesBySid(student.getId());
                String courseNames = scResult.getData();
                DefaultTableModel model = (DefaultTableModel)this.stats.getModel();
                model.addRow(new Object[]{student.getId(),student.getName(),courseNames,"出勤", UUID.randomUUID().toString()});
            }



        }




    }



    
    public teacherRecordStatusFrame(String date,String room) {
        initComponents();
        init(date,room);         //初始化
    }
    private void init(String date,String room){
        this.date=date;
        this.room=room;
        this.setTitle(room+"的考勤状况");
        UiUtil.setFrameCenter(this);
        this.jLabel6.setText(date);
        this.jLabel7.setText(room);
        this.setResizable(false);
        
        //设置考勤状态为组合框形式
        String[] items={"出勤","请假","旷课","迟到","早退"};
        JComboBox comboBox=new JComboBox(items);
        DefaultCellEditor dc=new DefaultCellEditor(comboBox);
        this.stats.getColumnModel().getColumn(3).setCellEditor(dc);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        submit = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        stats = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("日期");

        jLabel2.setText("班级");

        submit.setText("提交");
        submit.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });

        jButton2.setText("取消");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        stats.setBackground(new java.awt.Color(214, 217, 223));
        stats.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "学号", "姓名", "课程", "考勤状态", "id"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false
            };
            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        stats.setToolTipText("");
        stats.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(stats);
        if (stats.getColumnModel().getColumnCount() > 0) {
            stats.getColumnModel().getColumn(0).setResizable(false);
            stats.getColumnModel().getColumn(1).setResizable(false);
            stats.getColumnModel().getColumn(2).setResizable(false);
            stats.getColumnModel().getColumn(3).setResizable(false);
            stats.getColumnModel().getColumn(4).setMinWidth(0);
            stats.getColumnModel().getColumn(4).setMaxWidth(0);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 416, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(submit))
                .addGap(0, 10, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel6))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                .addGap(22, 22, 22))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(submit)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        //取消键
//        teacherRecordFrame trf=new teacherRecordFrame(teacherId);
//        this.dispose();
        trf.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
        // TODO add your handling code here:
//        DefaultTableColumnModel model = (DefaultTableColumnModel)this.stats.getColumnModel();
        StudentCourseController studentCourseController = new StudentCourseController();
        AttendanceController attendanceController = new AttendanceController();
        for(int cIndex = 0;cIndex < stats.getRowCount();cIndex++){
            String sid = (String)stats.getValueAt(cIndex, 0);
            String sname = (String)stats.getValueAt(cIndex, 1);
            String status = (String)stats.getValueAt(cIndex, 3);
            String aid = (String)stats.getValueAt(cIndex, 4);
            Result<StudentCourse> studentCourseBySid = studentCourseController.getStudentCourseBySid(sid);
            if (studentCourseBySid.getStatus() == ResultEnum.SUCCESS.getStatus()){
                //找到学生-课程
                StudentCourse studentCourse = studentCourseBySid.getData();
                attendanceController.addAttendanceByClass(sid, studentCourse.getCid(), date,status,teacherId, aClass.getId());
            }else{
                //找不到学生-课程
                attendanceController.addAttendanceByClass(sid, null, date,status,teacherId, aClass.getId());
            }



        }


        //点击提交按钮，将所有考勤信息按照
        // 日期-班级-学号-姓名-课程-考勤状态提交
        //        Class selectedItem1 = (Class)jComboBox1.getSelectedItem();
//        String selectedClassId = selectedItem1.getId();
//        AttendanceController attendanceController = new AttendanceController();
//        TeacherCourseController teacherCourseController = new TeacherCourseController();
//        Result<TeacherCourse> tc = teacherCourseController.getTCByTid(teacherId);
//        if(tc.getStatus() == ResultEnum.SUCCESS.getStatus()){
//            TeacherCourse data = tc.getData();
//            //String classId,String date,String status,String courseId,String teacherId
//            attendanceController.addAttendanceByClassAndCourse(selectedClassId,riqi,"出勤",data.getCid(),teacherId);
//        }else{
//            //String classId,String date,String status,String teacherId
//            attendanceController.addAttendanceByClass(selectedClassId,riqi,"出勤",teacherId);
//        }


        teacherViewFrame teacherViewFrame = this.trf.getTeacherViewFrame();
        teacherViewFrame.removeTable();
        teacherViewFrame.setTable(0,null);
        JOptionPane.showMessageDialog(null, "录入成功！");
        trf.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_submitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(teacherRecordStatusFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(teacherRecordStatusFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(teacherRecordStatusFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(teacherRecordStatusFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new teacherRecordStatusFrame("1000","1000").setVisible(true);
            }
        });
    }
    private String date;
    private String room;
    private Class aClass;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable stats;
    private javax.swing.JButton submit;
    // End of variables declaration//GEN-END:variables
    private String teacherId;
    private teacherRecordFrame trf;
}
